<template>
    <div class="main-cart-payment">
        <template v-if="!showStore">
            <div class="box address">
                <div class="hd"><h3>Delivery Location</h3><a @click="showAddress = true">Change</a></div>
                <div :style="{padding: '0px 16px 20px 16px'}" >
                    <van-row gutter="10" align="center">
                        <van-col style="width: 40px"><van-icon name="location" size="35" color="#FF5E00" /></van-col>
                        <van-col>
                            <div class="txt address">{{address.address_desc}}</div>
                            <div class="txt name">{{address.address_name}}</div>
                        </van-col>
                    </van-row>
                </div>
            </div>
            <div class="box date">
                <h3>Expected date & Time</h3>
                <div :style="{padding: '20px 16px'}"  >
                    <van-field
                        label-width="24px"
                        :style="{background: '#fff'}"
                        v-model="cart.delivery_date"
                        name="username"
                        placeholder="Select Date"
                        :rules="[{ required: true, message: 'Select Date is required' }]"
                        disabled
                        @click="showDate = true"
                    >
                        <template #left-icon><van-icon name="calendar-o" color="#6D3805" size="28" /></template>
                        <template #right-icon><van-icon name="arrow-down" color="#6D3805" size="20" /></template>
                    </van-field>
                    <van-row class="time" gutter="15">
                        <van-col :span="8" :class="{'col': true, 'selected': cart.delivery_time == time}" v-for="time in timeItems" @click="cart.delivery_time = time">
                            <div>{{time}}</div>
                        </van-col>
                    </van-row>
                </div>
            </div>
        </template>
        <div class="store">
            <van-row @click="showStore = true">
                <van-col :span="24" class="head">
                    <h3>In-Store Pick Up</h3>
                    <span class="tip">FREE</span>
                </van-col>
                <van-col :span="20" class="desc">
                    <span>Some Stores May Be Temporarily Unavalable.</span>
                </van-col>
                <van-col :span="4" class="icon">
                    <van-icon name="arrow-down" size="18" color="#6D3805" v-if="showStore" />
                    <van-icon name="arrow" size="18" color="#6D3805" v-else />
                </van-col>
            </van-row>
            <template v-if="showStore">
                <van-search v-model="value" placeholder="Search For Town, Street, Zip Code..." />
                <section class="box storelist" v-if="storeItems.length > 0">
                    <div class="list" v-for="item in storeItems" @click="setStore(item)">
                        <div class="address">
                            <div class="title">{{item.store_name}}</div>
                            <div class="title">{{item.store_desc}}</div>
                            <div class="distance">{{item.store_distance}}</div>
                        </div>
                        <van-icon name="arrow" class="icon" size="18" color="#6D3805" />
                    </div>
                </section>
            </template>
        </div>
        <div class="box items">
            <div class="list" :style="{padding: '30px 16px'}" @click="router.push({name: 'CartIndex'})" >
                <div>
                    <div class="title"><van-icon name="shopping-cart" size="30" :style="{marginRight: '5px'}" />see Itemes</div>
                </div>
                <van-icon name="arrow" class="icon" size="18" color="#6D3805" />
            </div>
        </div>
        <div class="box payment">
            <h3>Payment Method</h3>
            <div class="list" :style="{padding: '20px 32px 20px 16px'}" v-for="payment in paymentItems" @click="cart.payment_id = payment.payment_id" >
                <div>
                    <div class="lable">
                        <img :src="payment.payment_img" />{{payment.payment_name}}
                    </div>
                </div>
                <van-icon name="success" class="icon" size="24" v-if="cart.payment_id == payment.payment_id" color="#58A919" />
            </div>
        </div>
        <div class="box order">
            <h3>Order Sammery</h3>
            <div class="list" :style="{padding: '20px 32px 20px 16px'}"  >
                <div :style="{width: '100%'}">
                    <div class="cell">
                        <label>Subtotal</label><span class="total">${{cart.total_price}}</span>
                    </div>
                    <div class="cell">
                        <label>Tax</label><span class="total">${{cart.tax_price}}</span>
                    </div>
                    <div class="cell">
                        <label>In-Store Pick Up</label><span class="total">${{cart.runing_price}}</span>
                    </div>
                </div>
            </div>
            <div class="list" :style="{padding: '20px 32px 20px 16px'}"  >
                <div class="cell" :style="{padding: '0px'}">
                    <label><strong>Total:</strong></label><span class="total"><strong>${{cart.pay_amount}}</strong></span>
                </div>
            </div>
        </div>
        <div class="checkout" safe-area-inset-bottom>
            <div class="btn">
                <van-button round block type="primary" @click="onSubmit"><strong>CheckOut ${{cart.pay_amount}}</strong></van-button>
            </div>
        </div>
    </div>
    <van-calendar v-model:show="showDate" :show-confirm="false" @confirm="onConfirm" :min-date="minDate" />
    <van-action-sheet
        v-model:show="showAddress"
        :actions="addressItems"
        cancel-text="取消"
        close-on-click-action
        @select="setAddress"
    />
</template>

<script lang="ts" setup>
import { ref, watch, reactive, provide, onMounted  } from 'vue'
import applepay from '../../assets/applepay.png'
import { useStore } from 'vuex'
import { GetStoreList, GetAddressList, PostOrderConfirm, GetPayment } from '../../api/index'
import { N } from 'mockjs'
import { useRouter } from 'vue-router'
import moment from 'moment'
import { Toast, Dialog, Notify } from 'vant'

interface StoreInfo {
    store_name: string;
    store_desc: string;
    store_distance: string;
    store_id: number
}

const value = ref('')

const timeItems = ['8 AM - 11 AM','11 AM - 13 PM','13 PM - 15 PM','15 PM - 17 PM','17 PM - 19 PM','19 PM - 21 PM']
const showDate = ref<boolean>(false)

const router = useRouter()
const showStore = ref<boolean>(true)
const showAddress = ref<boolean>(false)
const store = useStore()
const cart = store.getters.getCart
const minDate = moment().add(-10, 'years').toDate()
const storeItems = ref<Array<StoreInfo>>([])

const setAddress = (item: any) => {
    address.value = item
}

const addressItems = ref<Array<{}>>([])

const paymentItems = ref<any>([])

const address = ref<{address_id: number, address_name: string, address_desc: string}>({
    address_id: 1,
    address_name: 'Lumajang, Jawa Timur',
    address_desc: 'Floor 4, Kartini Tower No 43'
})

const setStore = (storeinfo: StoreInfo) => {
    store.dispatch('setStore', storeinfo)
    showStore.value = false
}

const onConfirm = (value: string) => {
    showDate.value = false;
    cart.delivery_date = moment(value).format('YYYY-MM-DD')
};

const getStoreList = () => {
    GetStoreList({}).then((res: any)=>{
        storeItems.value = res.data
    })
}

const getAddressList = () => {
    GetAddressList({}).then((res: any)=>{
        addressItems.value = res.data.map((v: any) => {return {...v, name: v.address_name, subname: v.address_desc }})
    })
}

const getPayment = () => {
    GetPayment({}).then((res: any)=>{
        paymentItems.value = res.data
    })
}


const onSubmit = () => {

    if(cart.items.length == 0) {
        return Notify({ type: 'warning', message: '购物车空' });
    }

    if(cart.store == null) {
        return Notify({ type: 'warning', message: '请选择配送网点' });
    }

    if(cart.delivery_date == '') {
        return Notify({ type: 'warning', message: '请选择配送日期' });
    }

    if(cart.delivery_time == '') {
        return Notify({ type: 'warning', message: '请选择配送时间' });
    }
    const toast = Toast.loading({
                message: '订单提交中...',
                forbidClick: true,
            });
    PostOrderConfirm({...cart, address: address.value}).then(()=>{
        toast.clear();
        store.dispatch('initCart',{})
        router.push({name: 'MyOrders'})
    })
}

onMounted(() => {
    if(cart.items.length == 0){
        return router.push({name: 'ShopIndex'})
    }
    const toast = Toast.loading({
                message: '加载中...',
                forbidClick: true,
            });
    Promise.all([getAddressList(),getStoreList(),getPayment()]).then(()=>{
        toast.clear();
    })
    
})

</script>

<style lang="less" scoped>
.main-cart-payment {
    padding: 0px 16px;
    .store {
        padding: 20px 0px;
        .van-row {
            .head {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 12px;
                h3 {
                    font-weight: bold;
                    font-size: 22px;
                    line-height: 26px;
                    color: #6D3805;
                    padding: 0px;
                    margin: 0px;
                }
                .tip {
                        font-weight: bold;
                        font-size: 18px;
                        line-height: 22px;
                        color: #6D3805;
                    }
            }
            .desc {
                font-size: 18px;
                line-height: 22px;
                color: #6D3805;
            }
            .icon {
                display: flex;
                justify-content: center;
                align-items: center;
                i {
                    font-weight: bold;
                }
            }
        }

        .van-search {
            padding: 20px 0px;
        }
    }
    .box {
        background: #FFF4E9;
        border: 1px solid #FFE6CC;
        box-sizing: border-box;
        border-radius: 20px;
        margin-bottom: 20px;
        &.storelist {
            border-radius: 7px;
            margin-bottom: 0px;
        }
        &.date {
            .col {
                margin-top: 15px;
                div {
                    background: #fff;
                    border-radius: 7px;
                    font-size: 12px;
                    line-height: 16px;
                    text-transform: capitalize;
                    color: #6D3805;
                    padding: 10px;
                    box-shadow: 0px 0px 13px rgba(196, 196, 196, 0.25);
                }
                &.selected {
                    div{
                        background: #ff976a;
                        color: #fff;
                    }
                }
            }
        }
        &.address {
            .hd {
                padding: 16px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                h3{
                    padding: 0px;
                }
                a {
                    font-size: 18px;
                    line-height: 22px;
                    letter-spacing: -0.165px;
                    color: #FF5E00;
                }
            }
            .txt {
                font-size: 14px;
                line-height: 17px;
                color: #6D3805;
            }
        }
        h3 {
            font-weight: bold;
            font-size: 18px;
            line-height: 22px;
            text-transform: capitalize;
            color: #6D3805;
            padding: 16px;
            margin: 0px;
        }
        .list {
            padding: 20px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid rgba(109, 56, 5, 0.11);
            .lable {
                display: flex;
                align-items: center;
                img {
                    width: 40px;
                    margin-right: 10px;
                    background: #fff;
                }
                .van-icon {
                    margin-right: 10px;
                }
            }
            .title {
                display: flex;
                font-weight: bold;
                font-size: 18px;
                line-height: 22px;
                text-transform: capitalize;
                color: #6D3805;
                align-items: center;
            }
            .distance {
                margin-top: 16px;
                font-size: 18px;
                line-height: 22px;
                text-transform: capitalize;
                color: #6D3805;
            }
            .icon {
                font-weight: bold;
            }
            &:last-child {
                border-bottom: 0px;
            }
            .cell {
                display: flex;
                justify-content: space-between;
                font-size: 18px;
                line-height: 22px;
                letter-spacing: -0.165px;
                color: #6D3805;
                width: 100%;
                padding: 10px 0px;
            }
        }
    }
    .checkout {
        height: 80px;
        .btn {
            position: fixed;
            width: calc(100vw - 32px);
            margin: 0px 16px;
            bottom: 80px;
            left: 0px;
        }
    }

}
</style>
